package com.example.exercise.service.impl;


import com.example.exercise.exception.BusinessException;
import com.example.exercise.exception.ExceptionCode;
import com.example.exercise.mapper.BookMapper;
import com.example.exercise.model.Book;
import com.example.exercise.model.BookDonate;
import com.example.exercise.model.BookType;
import com.example.exercise.service.BookService;
import com.example.exercise.util.BookUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    private BookMapper bookMapper;


    //捐献请求
    @Override
    public String donate(List<Book> books, String username) {
        //捐献列表是否完整
        if (books.isEmpty()) {
            throw new BusinessException(ExceptionCode.ISNULL);
        }

        //集合获取所有的图书数据
        List<Book> existingISBNs = BookUtil.getAll();
        //遍历
        for (Book book : books) {
            //判断你的捐献列表图书信息是否完整(图书姓名，图书唯一ISBN,出版年份)
            if (book.getName() == null || book.getISBN() == null || book.getYear() == 0) {
                throw new BusinessException(ExceptionCode.INFORMATION);
            }
            if (book.getYear() < 2000) {//出版年份小于2000
                throw new BusinessException(ExceptionCode.OUTDATED_BOOK);
            }
            //检查书籍类型是否为教科书或者漫画
            if (book.getBookType().equals(BookType.TEXTBOOK) || book.getBookType().equals(BookType.CARTOON)) {
                throw new BusinessException(ExceptionCode.UNSUPPORTED_TYPE);
            }
            //查重校验证
            //判断图书唯一国际书号ISBN,是否已经存在
            if (existingISBNs.contains(book.getISBN())) {
                throw new BusinessException(ExceptionCode.DUPLICATE_BOOK);
            }
        }
        //捐献数量不能超过三本
        if (books.size() > 3) {
            throw new BusinessException(ExceptionCode.EXCEED_LIMIT);
        }

        //检查当前日期是否为每月1-10日
        LocalDateTime today = LocalDateTime.now();//现在的系统时间
        //捐赠图书只能在0-10开放捐赠
        //今天每月日子
        if (today.getDayOfMonth() < 1 || today.getDayOfMonth() > 10) {
            throw new BusinessException(ExceptionCode.INVALID_TIME);
        }

        //创建捐献记录
        BookDonate bookDonate = new BookDonate();
        bookDonate.setId(UUID.randomUUID().toString());
        bookDonate.setUsername(username);
        bookDonate.setBooks(books);//捐献列表
        bookDonate.setCreatTime(LocalDateTime.now());
        //生成捐献记录，保存书籍到馆藏
        bookMapper.save(bookDonate);
        //返回id
        return bookDonate.getId();
    }

}
